package com.mantru.iotpot.dishes

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.mantru.iotpot.Adapter.DishesChooseAdapter
import com.mantru.iotpot.R
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.databinding.ActivityDishesCreateChooseBinding

class DishesCreateChooseActivity : AppCompatActivity() {
    private val viewModel by viewModels<DishesCreateChooseViewModel>()
    private lateinit var binding: ActivityDishesCreateChooseBinding
    //adapter属于UI层，负责交互，留在Activity
    private var dishesChooseAdapter: DishesChooseAdapter? = null
    private var parentPosition: Int = -1 // 用于存储传递的 position
    private var sonPosition: Int = -1 // 用于存储传递的 position

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_create_choose)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()

        // 获取传递的 positionselectedFoodList
        parentPosition = intent.getIntExtra("parentPosition", -1)
        sonPosition = intent.getIntExtra("position", -1)
        viewModel.existName = intent.getStringExtra("existName").toString()
    }

    override fun onResume() {
        super.onResume()
        //获取食材数据
        val map: MutableMap<String, Any> = HashMap()
        map["count"] = 100
        viewModel.getHttpValue("GetSQLData_Vegetable_List_Base", map)
    }

    //初始化recyclerview
    private fun setRecyclerView(){
        dishesChooseAdapter = DishesChooseAdapter(this, R.layout.adapter_dishes_choose, viewModel.dishesChooseList.value ?: mutableListOf())
        binding.dishesChooseRecyclerview.apply {
            // 使用 FlexboxLayoutManager，设置方向为水平，并启用换行
            layoutManager = FlexboxLayoutManager(this@DishesCreateChooseActivity).apply {
                flexDirection = FlexDirection.ROW
                flexWrap = FlexWrap.WRAP
                alignItems = AlignItems.STRETCH
            }
            adapter = dishesChooseAdapter
        }
    }

    //设置控件交互事件
    private fun setContentAction(){

        //关闭按钮
        binding.dishesChooseBack.setOnClickListener {
            finish()
        }

        // 开启对 foodSearch 的监听
        viewModel.startListeningToFoodSearch()

        //搜索按钮
        binding.dishesChooseSearch.setOnClickListener {
            viewModel.performSearch()
        }

        //清空按钮
        binding.dishesChooseClear.setOnClickListener {
            viewModel.foodSearch.set("")
        }

        //取消按钮
        binding.dishesChooseCancel.setOnClickListener{
            finish()
        }

        //输入框
        binding.dishesChooseEdittext.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        //新增按钮
        binding.dishesChooseAdd.setOnClickListener{
            if ( viewModel.foodSearch.get()!!.toString().isEmpty() ){
                //Toast.makeText(this@DishesCreateChooseActivity, "请输入添加食材内容", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@DishesCreateChooseActivity, "请输入添加食材内容")
                return@setOnClickListener
            }
            //保存食材数据
            val map: MutableMap<String, Any> = HashMap()
            map["base_name"] = viewModel.foodSearch.get()!!.toString()
            viewModel.getHttpValue("SaveSQLData_Vegetable_Base", map)
        }

        //和adapter交互
        dishesChooseAdapter!!.setDishesChooseListener(object : DishesChooseAdapter.DishesChooseListener{
            @SuppressLint("NotifyDataSetChanged")
            override fun onChoose(position: Int) {
                val dishesChooseList = viewModel.dishesChooseList.value
                if (dishesChooseList != null && position < dishesChooseList.size) {
                    val selectedFood = dishesChooseList[position]
                    if (selectedFood.isSelected) {
                        // 如果选中，则添加到选中的列表中
                        viewModel.selectedFoodList.value?.clear()
                        viewModel.selectedFoodList.value?.add(selectedFood.name)
                    } else {
                        // 如果取消选中，则从选中的列表中移除
                        viewModel.selectedFoodList.value?.remove(selectedFood.name)
                    }
                    dishesChooseAdapter!!.notifyDataSetChanged()
                }
                //这里新增返回逻辑，点完就回去了
                val resultIntent = Intent()
                resultIntent.putExtra("foodName",
                    viewModel.selectedFoodList.value?.let { it1 -> ArrayList(it1) })
                resultIntent.putExtra("parentPosition", parentPosition)
                resultIntent.putExtra("position", sonPosition)
                setResult(RESULT_OK, resultIntent)
                finish()
            }
        })
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesChooseList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
                list?.let {
                    dishesChooseAdapter?.updateData(it)
                }
            }
    }
}